import React, { Component } from 'react';
import {
  Row,
  Col,
  Button,
  Upload,
  Modal,
  Spin,
  Popconfirm,
} from 'antd';
import { Map, List } from 'immutable';
import Image from 'components/Image'
import MessageDialog from './MessageDialog.js';
import RefundDialog from '../../component/RefundDialog.js'
import Refund from './Refund.js'
import Returned from './Returned.js'
import { QmIcon } from 'qm-ui';
import { afterSaleStatusEnum } from '../constant/enum.js';
import roleEnum from "constant/roleEnum.js";
import noop from 'util/noop'
import { defaultAvatorImage } from 'constant/image.js'
class OrderInfo extends Component {
    static defaultProps = {
        role:{ 
            bname:''
        },//角色
        order:Map({
            tate:0,// 当前订单进度
            needReturn:0,//1:需要退货，0:不需要
            reason:'',//售后原因
            returnProblem:'暂无'//问题说明
            
        }),
        messages:List.of(),
        appendSellerMsg:noop,
        //fetchRefundOrderInfo:noop,
    }
    constructor(props){
        super(props);
        /**
         * false：不通过，拒收，true：通过，收货，退款
         * 每个阶段对应不同的按钮loading状态
         */
        this.auditStatus = '';
        this.state = {
            visible:false,//留言
            previewImage: '',
            previewVisible: false,//预览凭证
            refundVisible:false,//退款确认
            refundInfoVisible:false,
            returnedVisible:false,
            loading:false,//按钮加载状态
        }
    }
    render() {

        const { order, messages, refund, refundLog, returnedLog, role } = this.props;
        const { visible, previewImage, previewVisible, refundInfoVisible, returnedVisible, refundVisible } = this.state;
        const { buttons,afterSaleStatus } = this.renderButtons(order,role);
        //其他说明信息，例如：商品退货方式，凭证等
        const restInfo = [];
        //退货方式：快递，上门自提
        if(order.get('shipName')){
            restInfo.push(
                <p key="way">商品退货方式：<span>{order.get('shipName')}</span></p>
            )
        }
        //凭据
        if(order.get('applyCredential')){
            restInfo.push(
                <p key="credential">申请凭据：<span>{order.get('applyCredential')}</span></p>
            )
        }
        //凭证图片
        if(order.get('voucher')){
            restInfo.push(
                <div key="voucher">
                    <span className="va-t">凭证：</span>
                     <Upload 
                        action="/do"
                        listType="picture-card"
                        fileList={this.transform2Imgs(order.get('voucher'))}
                        onPreview={this.handlePreview}
                        className="upload-qm un-deletable"
                    />
                     <Modal
                        visible={previewVisible}
                        footer={null}
                        onCancel={this.cancelPreview}
                    >
                        <Image src={previewImage} auto={true} style={{width:'100%'}}/>
                    </Modal>
                </div>
            )
        }
        return (
            <div className="order-info">
                <Row className="order-info-hd" key="orderHd">
                    <Col span={18}>
                        <div className="font-14">
                            <b>售后状态：</b>
                            <span className="t-red">
                                {afterSaleStatus}
                            </span>
                            
                        </div>
                    </Col>
                    <Col span={6}>
                        <div className="t-right">
                           {buttons}
                        </div>
                    </Col>
                </Row>
                 <Row className="order-info-bd" key="orderBd">
                    <Col span={24}>
                    <ul className="info-item">
                        <li key="reason">
                            <div className="avatar">
                                <Image src={order.get('userLogo') || defaultAvatorImage} height={32} width={32} auto={true} />
                            </div>
                            <p className="lh24">买家：{refund.getIn(['tradeOrder','buyNickName'])}</p>
                            <p>售后原因：<span className="t-red">{order.get('returnReasonName')}</span></p>
                            {restInfo}
                        </li>
                        <li className="bdb" key="desc">
                            <QmIcon type="liuyan" className="t-red"/>
                            <p className="lh24">问题说明：</p>
                            <p>{order.get('returnProblem') || '暂无'}</p>
                        </li>
                        <li key="message">
                            <QmIcon type="bianji" className="t-grayer"/>
                            <p className="lh24">卖家留言：
                                <span className="pull-right">
                                    <a href="javascript:;" disabled={messages.count() >=5} onClick={this.popupMessageDialog}>回复客户</a>
                                </span>
                            </p>
                            {messages.map((msg,index)=><p key={index}>{msg}</p>)}
                        </li>
                    </ul>
                    </Col>
                </Row>
                <MessageDialog
                    visible={visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                />
                {
                /*
                    退款操作不放在订单客服操作，由会计操作*/
                }
                <RefundDialog
                        refund={refund}
                        disabled={order.get('needReturn') == 0}
                        visible={refundVisible}
                        onOk={this.confirmRefund}
                        onCancel={this.cancelRefund}
                    />
                <Refund
                    title="退款单"
                    visible={refundInfoVisible}
                    onCancel={()=>{this.setState({refundInfoVisible:false})}}
                    refund={refundLog}
                />
                <Returned
                    title="退货单"
                    visible={returnedVisible}
                    onCancel={()=>{this.setState({returnedVisible:false})}}
                    returned={returnedLog}
                 />
            </div>
        );
    }
    /**
     * 图片分割成upload组件可以识别的图片对象 
     */
    transform2Imgs = (imgString) => {
        return imgString.split(',').map((img,index)=>{
            if(/^https?:\/\//.test(img)){
                img = img.replace(/https?:\/\//,"//");
            }else if (img.indexOf('//') != 0) {
                img = $CONST_HOST['v_oss_domain_img'] + img;
            }
            return {
                uid:index,
                name:'凭证图片'+index,
                status:'done',
                url:img
            }
        })
    }
    /**
     * 预览凭证图片
     */
    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        })
    }
    /**
     * 取消预览图片
     */
    cancelPreview = ()=>{
         this.setState({
            previewImage: '',
            previewVisible: false,
        })
    }
    /**
     * 添加售后进度状态，和相关操作按钮
     * @param order 订单信息
     * @param role 当前用户角色
     */
    renderButtons = (order, role) => {
        const buttons = [];

        //const { state, needReturn ,needRefund} = order;
        const state = order.get('state');
        const needReturn = order.get('needReturn');
        const needRefund = order.get('needRefund');
        //订单状态
        let afterSaleStatus = null;
        if(role){
            //订单及客服的角色
            if(role.bname === roleEnum.CustomerService){
                if(state === afterSaleStatusEnum.AUDITING.value) {
                    //待审核
                    buttons.push(
                        <Popconfirm key="auditFalse" title="您确定要拒绝该申请吗？" onConfirm={()=>{this.auditOrder(false)}}>
                            <Button  loading={this.state.loading && this.auditStatus === false} type="ghost">拒绝</Button>                        
                        </Popconfirm>,
                        <Popconfirm key="auditPass" title="您确定要通过该申请吗？" onConfirm={()=>{this.auditOrder(true)}}>
                            <Button loading={this.state.loading && this.auditStatus === true} type="primary" className="pushl">通过</Button>
                        </Popconfirm>
                    );
                    afterSaleStatus = afterSaleStatusEnum.AUDITING.name || '待审核'
                }else if((needReturn == 0 && state === afterSaleStatusEnum.AUDITED.value) || (needReturn === 1 && state === afterSaleStatusEnum.RECEIVEED.value)){
                    /*待退款按钮移走，给会计角色*/
                    afterSaleStatus = '待退款'
                }else if(needReturn == 1 && state === afterSaleStatusEnum.AUDITED.value){
                    buttons.push(
                        <Popconfirm key="destroy" title="您确定要取消吗？" onConfirm={this.cancelOrder}>
                            <Button type="ghost" loading={this.state.loading && this.auditStatus === false}>取消</Button>
                        </Popconfirm>,
                        <Popconfirm key="returned" title="您确定要收货吗？" onConfirm={this.receivedGoods}>
                            <Button type="primary" loading={this.state.loading && this.auditStatus === true} className="pushl">收货</Button>
                        </Popconfirm>
                    )
                    afterSaleStatus = '待收货'
                }else if(state === afterSaleStatusEnum.REFUND.value || state === afterSaleStatusEnum.FINISHED.value){
                    //需要退货
                    // if(needReturn){
                    //     buttons.push(
                    //         <Button key="viewReturned" type="ghost" onClick={this.showReturnedInfo}>查看退货单</Button>
                    //     )
                    // }
                    //需要退款
                    if(needRefund){
                        buttons.push(
                            <Button key="viewRefund" type="ghost" className="pushl" onClick={this.showRefundInfo}>查看退款单</Button>
                        )
                    }
                    
                    afterSaleStatus = afterSaleStatusEnum.FINISHED.name || '退款成功'
                }else if(state === afterSaleStatusEnum.UNAUDITED.value ){
                    afterSaleStatus = '已拒绝'
                }else if(state === afterSaleStatusEnum.CANCEL.value){
                    afterSaleStatus = "已取消"
                }
            }else if(role.bname === roleEnum.Accounting){
                //会计角色
                if((needReturn == 0 && state === afterSaleStatusEnum.AUDITED.value) || (needReturn === 1 && state === afterSaleStatusEnum.RECEIVEED.value)){
                    
                    buttons.push(
                        <Button key="refund" type="primary" onClick={this.popupRefundDialog}>退款</Button>
                    )
                    afterSaleStatus = '待退款'
                }
            }
        }
        

        return { buttons,afterSaleStatus};
    }
    popupRefundDialog = () => {
        this.setState({
            refundVisible:true
        });
    }

    confirmRefund = (values) => {
        return this.props.confirmRefund(values)
            .then((resp)=>{
                this.cancelRefund();
                return resp;
            })
            .catch((er)=>{
                return Promise.reject(er);
            });
       
    }

    cancelRefund = () => {
        this.setState({
            refundVisible:false
        })
    }
    /**
     * 弹出留言框
     */
    popupMessageDialog = () => {
        this.setState({
            visible:true
        })
    }
    /**
     * 保存留言
     */
    handleOk = (message) => {
        this.props.appendSellerMsg(message);
        this.handleCancel();
    }
    /**
     * 取消留言
     */
    handleCancel = () => {
        this.setState({
            visible:false
        })
    }

    showRefundInfo = () => {
        this.setState({
            refundInfoVisible:true
        })
    }

    showReturnedInfo = () => {
        this.setState({
            returnedVisible:true
        });
    }
    /**
     * 审核订单
     * true：审核通过
     * false：不通过
     * @param checkout boolean
     */
    auditOrder = (checkout) => {
        this.auditStatus = checkout;
        this.setState({loading:true})
        this.props.auditOrder(checkout)
        .then(()=>{
            this.setState({loading:false})
            this.auditStatus = ''
        })
        .catch(() =>{
            this.setState({loading:false})
            this.auditStatus = ''
        });
    }
    /**
     * 关闭订单
     */
    cancelOrder = () => {
        this.auditStatus = false;
        this.setState({loading:true})
        this.props.cancelOrder()
         .then(()=>{
            this.setState({loading:false})
            this.auditStatus = ''
        })
        .catch(() =>{
            this.setState({loading:false})
            this.auditStatus = ''
        });
    }
    /**
     * 签收退货
     */
    receivedGoods = () =>{
        this.auditStatus = true;
        this.setState({loading:true})
        this.props.receivedGoods()
        .then(()=>{
            this.setState({loading:false})
            this.auditStatus = ''
        })
        .catch(() =>{
            this.setState({loading:false})
            this.auditStatus = ''
        });
    }
}

export default OrderInfo;